package core

import (
	"flag"
	"fmt"
	"gitee.com/hwpro/cvecompetition/global"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"log"
	"os"
)

const defaultCfgPath = "config/config.yaml"

func parseOption(flags *flag.FlagSet, args []string) error {
	flags.IntVar(&global.FlagOption.Port, "server port", 8080, "the server port")
	flags.StringVar(&global.FlagOption.ConfigPath, "config path", defaultCfgPath, "the server config file path")
	if err := flags.Parse(args); err != nil {
		return err
	}
	return nil
}

func init() {
	if err := parseOption(flag.CommandLine, os.Args[1:]); err != nil {
		log.Fatal(fmt.Errorf("parse flag options failure %v", err))
	}
	if err := parseServerConfig(); err != nil {
		log.Fatal(fmt.Errorf("parse config path failure %v", err))
	}
}

func parseServerConfig() error {
	vp := viper.New()
	vp.SetConfigFile(global.FlagOption.ConfigPath)
	if err := vp.ReadInConfig(); err != nil {
		return err
	}
	vp.WatchConfig()
	vp.OnConfigChange(func(in fsnotify.Event) {
		fmt.Println("config file change:", in.Name)
		if err := vp.Unmarshal(&global.GmsConfig); err != nil {
			fmt.Println(err)
		}
	})
	if err := vp.Unmarshal(&global.GmsConfig); err != nil {
		return err
	}
	global.GmsViper = vp
	return nil
}
